<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class Shop extends Model
{
    use HasFactory;
    const REDIS_PREFIX="allenapi_shop_list_";
    protected $table = "shop";
    protected $guarded = [];
    public static function refreshData2Redis($id){
        if(empty($id)){
            return null;
        }
        $me=self::where('origin_id',$id)->first();
        if(!empty($me)){
            $fields=[
                'origin_id'=>$me->origin_id,
                'origin_name'=>$me->origin_name,
            ];
            Redis::SET(self::REDIS_PREFIX.$id,json_encode($fields));
        }else{
            $origin=self::shopDB_queryFromId($id);
            if(!empty($origin)){
                $fields=[
                    'origin_id'=>$origin->site_id,
                    'origin_name'=>$origin->site_name,
                ];
                $me=self::create($fields);
                Redis::SET(self::REDIS_PREFIX.$id,json_encode($fields));
            }
        }
        return $me;
    }
    public static function newShop($data){
        $id=$data['shop_id']??null;
        if(empty($id)){
            return null;
        }
        $me=Redis::get(self::REDIS_PREFIX.$id);
        if(!empty($me)){
            return json_decode($me);
        }
        $me=self::where('origin_id',$id)->first();
        if(!empty($me)){
            $fields=[
                'origin_id'=>$me->origin_id,
                'origin_name'=>$me->origin_name,
            ];
            Redis::SET(self::REDIS_PREFIX.$id,json_encode($fields));
        }else{
            $origin=self::shopDB_queryFromId($id);
            if(!empty($origin)){
                $fields=[
                    'origin_id'=>$origin->site_id,
                    'origin_name'=>$origin->site_name,
                ];
                $me=self::create($fields);
                Redis::SET(self::REDIS_PREFIX.$id,json_encode($fields));
            }
        }
        return $me;
    }
    public static function setPoints($id,$oprate){
        $point=self::where('origin_id',$id)->value('points');
        $points=[
            $point,
            $point
        ];
        switch($oprate['flag']){
            case '+':{
                $points[1]=bcadd($points[1],$oprate['value']);
                break;
            }
            case '-':{
                $points[1]=bcsub($points[1],$oprate['value']);
                break;
            }
            default:{
                return null;
            }
        }
        self::where('origin_id',$id)->update([
            'points'=>$points[1]
        ]);
        return $points;
    }
    private static function shopDB_queryFromId($id){
        return DB::connection('shop')->table('shop')->where('site_id',$id)->first();
    }
}
